<template>
  <div class="main">
    <button @click="exportExcel">导出EXCEL</button>
    <CartSubject v-for="(item,i)  in  cart"
                 :index=" i+1"
                 :key="item.title"
                 :title="item.title"
                 :data="item.data"></CartSubject>

  </div>

</template>

<script>
import {export_json_to_excel} from "../vendor/Export2Excel"
import CartSubject from "../components/CartSubject";
import { createNamespacedHelpers } from "vuex";
let { mapState, mapGetters } = createNamespacedHelpers("subject");
export default {
  components: {
    CartSubject
  },
  computed: {
    ...mapState(["subjectCartList"]),
    ...mapGetters([
      "cat_danxuanlist",
      "cat_duoxuanlist",
      "cat_panduanlist",
      "cat_jiandalist"
    ])
  },
  methods: {
    initSubjectGroupDate() {
      this.cart = [];
      if (this.checkArrayHasVal(this.cat_danxuanlist))
        this.cart.push({
          title: "单选题",
          data: this.cat_danxuanlist
        });

      if (this.checkArrayHasVal(this.cat_duoxuanlist))
        this.cart.push({
          title: "多选题",
          data: this.cat_duoxuanlist
        });

      if (this.checkArrayHasVal(this.cat_panduanlist))
        this.cart.push({
          title: "判断题",
          data: this.cat_panduanlist
        });

      if (this.checkArrayHasVal(this.cat_jiandalist))
        this.cart.push({
          title: "简答题",
          data: this.cat_jiandalist
        });
    },
    fmtOptions(arr){
      if(!arr) return ''
      return arr.map(r=>[r.val].join('|'))
    },
    export2E(){
      let data=[];
      this.cart.forEach(r=>{
        r.data.forEach(rr=>{
          data.push([r.title,rr.title,this.fmtOptions(rr.options),rr.auswer,rr.desc])
        })
      })
      return data
    },

     exportExcel() {
      require.ensure([], () => {
        const tHeader = ["题型","标题","选项","答案","解析"]; //生成Excel表格的头部标题栏
        const data = this.export2E(); //生成Excel表格的内容栏（根据自己的数据内容属性填写）
        const filename = "题目"+ new Date().toLocaleDateString()
        export_json_to_excel(tHeader, data, filename); //这里可以定义你的Excel表的默认名称
      });
    },
   
  },
  data() {
    return {
      cart: []
    };
  },
  mounted() {
    this.initSubjectGroupDate();
  },
  watch: {
    subjectCartList() {
      this.initSubjectGroupDate();
    }
  }
};
</script>

<style lang='scss'>
.main {
  width: 1000px;
  border: 1px solid red;
  margin: 100px auto;
  font-size: 16px;
}
li {
  list-style: none;
}
.item {
  padding: 10px;
  border-bottom: 1px solid #ccc;
  position: relative;
}
.subject-cart {
  position: fixed;
  right: 0;
  width: 20px;
  padding: 10px;
  background: rgb(5, 136, 138);
  top: 50%;
  color: white;
  transform: translateY(-50%);
}

.btn-add {
  position: absolute;
  right: 10px;
  top: 10px;
}
</style>